<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>作业2</title>
    <link
      rel="stylesheet"
      href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css"
    />
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
  </head>
  <body>
    <button
      id="addBtn"
      type="button"
      class="btn btn-default"
      data-toggle="modal"
      data-target="#addModal"
    >
      增加
    </button>
    <table id="table" class="table table-bordered">
      <thead>
        <tr>
          <th>名称</th>
          <th>城市</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <!-- <tr>
          <td>Tanmay</td>
          <td>Bangalore</td>
          <td>
            <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#delModal">删除</button>
            <button type="button" class="btn btn-info" data-toggle="modal" data-target="#modModal">修改</button>
          </td>
        </tr>
        <tr>
          <td>Sachin</td>
          <td>Mumbai</td>
          <td>
            <button type="button" class="btn btn-danger">删除</button>
            <button type="button" class="btn btn-info">修改</button>
          </td>
        </tr> -->
      </tbody>
    </table>
    <div id="modalBox"></div>
    <script>
      const data = [
        { id: 1, name: "李四", city: "重庆" },
        { id: 2, name: "张三", city: "成都" },
      ];
      //   创建ID
      let index = 100;
      function createId() {
        return ++index;
      }
      //   动态渲染
      renderTable(data);
      //   点击删除，渲染模态框
      $("#table").on("click", "#delBtn", function (event) {
        $("#modalBox").empty();
        const dataId = parseInt($(event.target).attr("data-id"));
        const currentItem = data.find((item) => item.id === dataId);
        $("#modalBox").append(`
          <!-- 模态框（Modal） -->
        <div
          class="modal fade"
          id="delModal"
          tabindex="-1"
          role="dialog"
          aria-labelledby="myModalLabel"
          aria-hidden="true"
        >
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <button
                  type="button"
                  class="close"
                  data-dismiss="modal"
                  aria-hidden="true"
                >
                  &times;
                </button>
                <h4 class="modal-title" id="myModalLabel">确认删除？</h4>
              </div>
              <div class="modal-body">${currentItem.name}  ${currentItem.city}</div>
              <div class="modal-footer">
                <button
                  type="button"
                  class="btn btn-default"
                  data-dismiss="modal"
                >
                  关闭
                </button>
                <button id="confirmBtn" data-id="${currentItem.id}" type="button" class="btn btn-primary">确认</button>
              </div>
            </div>
            <!-- /.modal-content -->
          </div>
          <!-- /.modal -->
        </div>
          `);
      });
      //   点击 确认删除
      $("#modalBox").on("click", "#delModal #confirmBtn", function (event) {
        $("#delModal").modal("hide");
        const dataId = parseInt($(event.target).attr("data-id"));
        for (let i = 0; i < data.length; ++i) {
          if (dataId === data[i].id) {
            data.splice(i, 1);
          }
        }
        renderTable(data);
      });
      //   点击 修改，渲染模态框
      $("#table").on("click", "#modBtn", function (event) {
        $("#modalBox").empty();
        const dataId = parseInt($(event.target).attr("data-id"));
        const currentItem = data.find((item) => item.id === dataId);
        $("#modalBox").append(`
          <!-- 模态框（Modal） -->
        <div
          class="modal fade"
          id="modModal"
          tabindex="-1"
          role="dialog"
          aria-labelledby="myModalLabel"
          aria-hidden="true"
        >
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <button
                  type="button"
                  class="close"
                  data-dismiss="modal"
                  aria-hidden="true"
                >
                  &times;
                </button>
                <h4 class="modal-title" id="myModalLabel">修改</h4>
              </div>
              <div class="modal-body">

      <form class="form-horizontal" role="form">
        <div class="form-group">
          <label for="firstname" class="col-sm-2 control-label">名称：</label>
          <div class="col-sm-5">
            <input
              type="text"
              class="form-control"
              id="name"
              placeholder="请输入名称"
              value="${currentItem.name}"
            />
            <span class="help-block has-error"
            ></span
          >
          </div>

        </div>
        <div class="form-group">
          <label for="lastname" class="col-sm-2 control-label">城市：</label>
          <div class="col-sm-5">
            <select name="" id="city" class="form-control"
            >
              <option value="成都" selected>成都</option>
              <option value="重庆">重庆</option>
              <option value="北京">北京</option>
              <option value="上海">上海</option>
              <option value="广州">广州</option>
              <option value="深圳">深圳</option>
            </select>
          </div>
        </div>
      </form>
                  </div>
              <div class="modal-footer">
                <button
                  type="button"
                  class="btn btn-default"
                  data-dismiss="modal"
                >
                  关闭
                </button>
                <button id="confirmBtn" data-id="${currentItem.id}" type="button" class="btn btn-primary">提交更改</button>
              </div>
            </div>
            <!-- /.modal-content -->
          </div>
          <!-- /.modal -->
        </div>
          `);
        $("#city").val(currentItem.city);
      });
      //   表单验证，名字 空
      $("#modalBox").on("blur", "#name", function (event) {
        const value = $(event.target).val();
        if (!value) {
          $("#name").parent().addClass("has-error");
          $("#name").next().empty();
          $("#name").next().append(`请输入名称！`);
        } else {
          $("#name").parent().removeClass("has-error");
          $("#name").parent().addClass("has-success");
          $("#name").next().empty();
        }
      });
      //   点击 确认修改
      $("#modalBox").on("click", "#modModal #confirmBtn", function (event) {
        if (!$("#name").val()) {
          $("#name").parent().addClass("has-error");
          $("#name").next().empty();
          $("#name").next().append(`请输入名称！`);
          return;
        }
        $("#modModal").modal("hide");
        const dataId = parseInt($(event.target).attr("data-id"));
        for (let i = 0; i < data.length; ++i) {
          if (dataId === data[i].id) {
            data[i].name = $("#name").val();
            data[i].city = $("#city").val();
          }
        }
        renderTable(data);
      });

      //   点击 新增，渲染模态框
      $("#addBtn").on("click", function (event) {
        $("#modalBox").empty();
        $("#modalBox").append(`
          <!-- 模态框（Modal） -->
        <div
          class="modal fade"
          id="addModal"
          tabindex="-1"
          role="dialog"
          aria-labelledby="myModalLabel"
          aria-hidden="true"
        >
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <button
                  type="button"
                  class="close"
                  data-dismiss="modal"
                  aria-hidden="true"
                >
                  &times;
                </button>
                <h4 class="modal-title" id="myModalLabel">新增</h4>
              </div>
              <div class="modal-body">

      <form class="form-horizontal" role="form">
        <div class="form-group">
          <label for="firstname" class="col-sm-2 control-label">名称：</label>
          <div class="col-sm-5">
            <input
              type="text"
              class="form-control"
              id="name"
              placeholder="请输入名称"
              value=""
            />
            <span class="help-block"
            ></span
          >
          </div>

        </div>
        <div class="form-group">
          <label for="lastname" class="col-sm-2 control-label">城市：</label>
          <div class="col-sm-5">
            <select name="" id="city" class="form-control"
            >
              <option value="成都" selected>成都</option>
              <option value="重庆">重庆</option>
              <option value="北京">北京</option>
              <option value="上海">上海</option>
              <option value="广州">广州</option>
              <option value="深圳">深圳</option>
            </select>
          </div>
        </div>
      </form>
                  </div>
              <div class="modal-footer">
                <button
                  type="button"
                  class="btn btn-default"
                  data-dismiss="modal"
                >
                  关闭
                </button>
                <button id="confirmBtn" type="button" class="btn btn-primary">确认</button>
              </div>
            </div>
            <!-- /.modal-content -->
          </div>
          <!-- /.modal -->
        </div>
          `);
      });
      //   点击 确认增加
      $("#modalBox").on("click", "#addModal #confirmBtn", function (event) {
        if (!$("#name").val()) {
          $("#name").parent().addClass("has-error");
          $("#name").next().empty();
          $("#name").next().append(`请输入名称！`);
          return;
        }
        $("#addModal").modal("hide");
        const addItem = {
          id: createId(),
          name: $("#name").val(),
          city: $("#city").val(),
        };
        data.push(addItem);
        renderTable(data);
      });

      //   动态渲染函数
      function renderTable(data) {
        $("tbody").empty();
        for (let i = 0; i < data.length; ++i) {
          $("tbody").append(`
          <tr>
            <td>${data[i].name}</td>
            <td>${data[i].city}</td>
            <td>
              <button  id="delBtn" data-id=${data[i].id} type="button" class="btn btn-danger" data-toggle="modal" data-target="#delModal">删除</button>
              <button id="modBtn" data-id=${data[i].id} type="button" class="btn btn-info" data-toggle="modal" data-target="#modModal">修改</button>
            </td>
          </tr>
        `);
        }
      }
    </script>
  </body>
</html>
